<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 14px">文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form inline :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="obj.cate_name" :value="obj.id" v-for="obj in artCates" :key="obj.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="choseFn">筛选</el-button>
            <el-button type="info" size="small" @click="resetFn">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialogFn">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题">
          <template slot-scope="scope">
            <el-link type="primary" @click="watchDetail(scope.row.id)"><span>{{ scope.row.title }}</span></el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template slot-scope="scope">
            <span>{{ $dateFormat(scope.row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="watchDetail(scope.row.id)">查看文章</el-button>
            <el-button type="danger" size="small" @click="delArt(scope.row.id)">删除文章</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 文章表格区域 -->
      <el-dialog title="发表文章" :visible.sync="pubDialogVisible" ref="dialogRef" fullscreen :before-close="handleClose"
        @close="dialogCloseFn">
        <!-- 发布文章的对话框 -->
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
              <el-option :label="obj.cate_name" :value="obj.id" v-for="obj in artCates" :key="obj.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <quill-editor v-model="pubForm.content" @blur="contentChangeFn"></quill-editor>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
            <!-- 用来显示封面的图片 -->
            <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" @click="selCoverFn" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="onCoverChangeFn" />
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="selCoverFn">+ 选择封面</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="pubArticleFn('已发布')">发布</el-button>
            <el-button type="info" @click="pubArticleFn('草稿')">存为草稿</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChangeFn" @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size.sync="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%" style="margin-left: 30px">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ $dateFormat(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 文章的封面 -->
      <img :src="baseURL + artDetail.cover_img" alt="" v-if="artDetail.cover_img" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import article from '@/api/article'
// 图片导入默认解析成本地url路径地址
import picPath from '../../assets/images/cover.jpg'
import { baseUrl } from '@/utils/request'

export default {
  name: 'ArtList',
  components: {},
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      baseURL: baseUrl,
      pubDialogVisible: false,
      detailVisible: false,
      artCates: [],
      artList: [], // 文章的列表数据
      total: 0, // 总数据条数
      artDetail: {},
      // ...其他
      pubForm: { // 表单的数据对象
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubFormRules: { // 表单的验证规则对象
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择封面', trigger: 'change' }]
      }
    }
  },
  computed: {},
  watch: {},
  methods: {
    showPubDialogFn () {
      this.pubDialogVisible = true
    },

    // 发布文章对话框关闭前的回调
    handleClose (done) {
      this.$confirm('此操作将导致文章信息的丢失,是否继续?', '提示', { type: 'warning' }).then(() => {
        done()
      }).catch(() => {
        this.$message.info('取消关闭')
      })
    },

    // 获取文章分类
    async getArtCate () {
      const { data: res } = await article.getCateList()
      this.artCates = res.data
    },

    // 选择图片
    selCoverFn () {
      this.$refs.iptFileRef.click()
    },

    onCoverChangeFn (e) {
      const files = e.target.files
      if (files.length !== 0) {
        // 已上传
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.src = url
      } else {
        this.pubForm.cover_img = null
        this.$refs.imgRef.src = picPath
      }
      this.$refs.pubFormRef.validateField('cover_img')
    },

    // 发布或存为草稿事件
    pubArticleFn (str) {
      // str为已发布或草稿
      this.pubForm.state = str
      this.$refs.pubFormRef.validate(async valid => {
        if (valid) {
          const fd = new FormData()
          fd.append('title', this.pubForm.title)
          fd.append('cate_id', this.pubForm.cate_id)
          fd.append('content', this.pubForm.content)
          fd.append('cover_img', this.pubForm.cover_img)
          fd.append('state', this.pubForm.state)
          const { data: res } = await article.addArticle(fd)
          if (res.code === 0) {
            this.resetFn()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
          // 关闭对话框
          this.dialogCloseFn()
        } else {
          return false
        }
      })
    },

    // 富文本编辑器触发该方法
    contentChangeFn () {
      this.$refs.pubFormRef.validateField('content')
    },

    // 关闭对话框
    dialogCloseFn () {
      this.pubDialogVisible = false
      // 清空表单
      this.$refs.pubFormRef.resetFields()
      // 图片不受v-model影响，手动设置
      this.$refs.imgRef.src = picPath
    },

    // 获取文章列表
    async getArtList () {
      const { data: res } = await article.getArtList(this.q)
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      } else {
        this.$message.error(res.message)
      }
    },

    // 查看文章
    async watchDetail (id) {
      this.detailVisible = true
      const { data: res } = await article.getArtDetailById(id)
      if (res.code === 0) {
        this.artDetail = res.data
      } else {
        this.detailVisible = false
        this.$message.error(res.message)
      }
    },

    // 删除文章
    delArt (id) {
      this.$confirm('您确定永久删除该文章吗?', '提示').then(async () => {
        const { data: res } = await article.deleteArtById(id)
        if (res.code === 0) {
          this.total--
          if (this.total === 0) {
            this.getArtList()
            return this.$message.success(res.message)
          }
          if (this.total % this.q.pagesize === 0) {
            this.q.pagenum = this.total / this.q.pagesize
          }
          this.getArtList()
          this.$message.success(res.message)
        } else {
          this.$message.info(res.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除!')
      })
    },

    // 筛选
    choseFn () {
      this.q.pagenum = 1
      this.q.pageSize = 2
      this.getArtList()
    },

    // 重置
    resetFn () {
      this.q.cate_id = ''
      this.q.state = ''
      this.q.pagenum = 1
      this.q.pageSize = 2
      this.getArtList()
    },

    handleSizeChangeFn (val) {
      this.q.pagesize = val
      this.q.pagenum = 1
      this.getArtList()
    },

    handleCurrentChangeFn (val) {
      this.q.pagenum = val
      this.getArtList()
    }
  },
  created () {
    this.getArtCate()
    this.getArtList()
  },
  mounted () {

  }
}
</script>
<style scoped lang="less">
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .btn-pub {
    margin-top: 5px;
  }
}

::v-deep .ql-editor {
  min-height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;

  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
::v-deep .detail-box {
  img {
    width: 500px;
  }
}
</style>
